import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";

var w = window.innerWidth, h = window.innerHeight
var camera, scene, renderer, mesh
function init() {
  scene = new THREE.Scene()

  camera = new THREE.PerspectiveCamera(45, w / h, 1, 10000)
  camera.position.set(0, 60, 100)
  camera.up.y = 1
  // camera.lookAt(scene.position)

  renderer = new THREE.WebGLRenderer()
  // renderer.setClearColor(0x3f5e6a)
  renderer.shadowMap.enabled = true
  renderer.shadowMap.type = THREE.PCFSoftShadowMap
  renderer.setSize(w, h)
  document.body.appendChild(renderer.domElement)

  createGeometry()
  createLight()
}
var mesh2
function createGeometry() {

  var plan = new THREE.PlaneGeometry(600,600,300,300)
  plan.computeVertexNormals()
  var material1 = new THREE.MeshLambertMaterial( { color: 0xeeeeee, side:THREE.DoubleSide } )
  var mesh1 = new THREE.Mesh(plan,material1)
  mesh1.rotation.x = -0.5 * Math.PI
  mesh1.position.y = -20
  mesh1.receiveShadow = true
  scene.add(mesh1)

  var axis = new THREE.AxesHelper(200)
  axis.add(mesh1)
  scene.add(axis)

  var box = new THREE.BoxGeometry(10,10,10,12,12,12)
  box.computeVertexNormals()
  var material2 = new THREE.MeshLambertMaterial({color:0x8edee2,side:THREE.DoubleSide})
  mesh2 = new THREE.Mesh(box,material2)
  mesh2.castShadow = true
  scene.add(mesh2)
}
var light2
let x = -300
function createLight(){
  var light1 = new THREE.AmbientLight(0xffffff,0.1)
  scene.add(light1)

  light2 = new THREE.DirectionalLight(0xffffff,0.6)
  light2.position.set(x,160,30)
  light2.castShadow = true
  scene.add(light2)
}
function animate() {
  if(mesh2){
    mesh2.rotation.x += 0.02
    mesh2.rotation.y += 0.02
  }
  if(light2){
    if(x>300) return
    x++
    light2.position.set(x,160,30)
  }
  renderer.render(scene, camera)
  requestAnimationFrame(animate)
}

init()
animate()
// /** --------------------鼠标控件对象--------------------- */
let controls = new OrbitControls(camera, renderer.domElement); //创建控件对象
controls.addEventListener("change", animate); //监听鼠标、键盘事件
